package org.wenhuayuan.project.main.fragment

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.text.format.Formatter
import android.util.Log
import android.util.SparseArray
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import kotlinx.android.synthetic.main.fragment_home.*
import org.wenhuayuan.library.resful.HiCallback
import org.wenhuayuan.library.resful.HiResponse
import org.wenhuayuan.project.common.uicomp.HiBaseFragment
import org.wenhuayuan.project.main.MainActivity
import org.wenhuayuan.project.main.R
import org.wenhuayuan.project.main.fragment.home.HomeTabFragment
import org.wenhuayuan.project.main.http.ApiFactory
import org.wenhuayuan.project.main.http.api.HomeApi
import org.wenhuayuan.project.main.model.TabCategory
import org.wenhuayuan.uilibrary.tab.bottom.HiTabBottomLayout
import org.wenhuayuan.uilibrary.tab.top.HiTabTopInfo
import java.text.SimpleDateFormat
import java.util.*

class HomePageFragment : HiBaseFragment() {
    private var tabTabSelectIndex: Int = 0
    private val selectTabIndex: Int=0

    override fun getLayoutRes(): Int {
        return R.layout.fragment_home
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        getAndShowInfoDevice() // 获取设备信息
        //
        HiTabBottomLayout.clipBottomPadding(view_pager)
        queryTabList()
    }

    //踩坑：如果当前的页面不存在，view被杀死回收，但是还在做网络请求，然后请求成功之后更新UI，则必然报错
    //踩坑：所以在更新之前要判断页面是否还存在
    private fun queryTabList() {
        ApiFactory.create(HomeApi::class.java).queryTabList().enqueue(object:HiCallback<List<TabCategory>>{
            override fun onSuccess(response: HiResponse<List<TabCategory>>) {
                val data = response.data
                if (response.successful()) {
                    updateUI(data!!)
                }

            }

            override fun onFailed(throwable: Throwable) {
            }
        })
    }

    private fun updateUI(data: List<TabCategory>) {
        //踩坑：所以在更新之前要判断页面是否还存在
        if (!isAlive) {
            return
        }

        val topTabs = mutableListOf<HiTabTopInfo<Int>>()
        data.forEachIndexed { _, tabCategory ->
            val defaultColor = ContextCompat.getColor(context!!, R.color.color_333)
            val selectColor = ContextCompat.getColor(context!!, R.color.color_dd2)
            val tabTopInfo = HiTabTopInfo<Int>(tabCategory.categoryName, defaultColor, selectColor)
            topTabs.add(tabTopInfo)
        }
        val topTabLayout = top_tab_layout
        topTabLayout.inflateInfo(topTabs!! as List<HiTabTopInfo<*>>)
        topTabLayout.defaultSelected(topTabs[selectTabIndex])
        topTabLayout.addTabSelectedChangeListener { index, prevInfo, nextInfo ->
            // 点击之后选中的下标
            if (view_pager.currentItem != index) {
                view_pager.setCurrentItem(index, false)
            }
        }
        val homePagerAdapter = HomePagerAdapter(childFragmentManager, data)
        view_pager.adapter = homePagerAdapter
        view_pager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                // 这方法被触发有两种可能
                // 1，切换顶部tab 2，手动滑动翻页

                if (position != tabTabSelectIndex) {
                    // 如果是第二种，通知进行切换
                    topTabLayout.defaultSelected(topTabs[position])
                    tabTabSelectIndex = position
                }


            }
        })
//        view_pager.adapter.up
    }


    inner class HomePagerAdapter(fm: FragmentManager?, private val tabs:List<TabCategory>)
        : FragmentPagerAdapter(fm!!) {
        private val fragments = SparseArray<Fragment>(tabs.size)
        override fun getItem(position: Int): Fragment {
            var fragment = fragments.get(position, null)
            if (null == fragment) {
                fragment = HomeTabFragment.newInstance(tabs[position].categoryId)
                fragments.put(position, fragment)
            }

            return fragment
        }

        override fun getCount(): Int {
            return tabs.size
        }
    }


    private fun getAndShowInfoDevice() {
        val formatter = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.CHINA)
        val LAUNCH_TIME = formatter.format(Date())
        val sb = StringBuilder()
        sb.append("brand= ${Build.BRAND}\n")// huawei,xiaomi
        sb.append("rom= ${Build.MODEL}\n") //sm-G9550
        sb.append("os= ${Build.VERSION.RELEASE}\n")//9.0
        sb.append("sdk= ${Build.VERSION.SDK_INT}\n")//28
        sb.append("M=${Build.VERSION_CODES.M} -- N=${Build.VERSION_CODES.N} -- O=${Build.VERSION_CODES.O} -- P=${Build.VERSION_CODES.P} -- Q=${Build.VERSION_CODES.Q} -- R=${Build.VERSION_CODES.R}\n")//28
        sb.append("launch_time= ${LAUNCH_TIME}\n")//启动APP的时间
        sb.append("crash_time= ${formatter.format(Date())}\n")//crash发生的时间
//        sb.append("forground=\n ${ActivityManager.instance.front}\n")//应用处于前后台
        sb.append("thread= ${Thread.currentThread().name}\n")//异常线程名
        sb.append("cpu_arch= ${Build.CPU_ABI}\n")//armv7 armv8

        //app 信息
        val packageInfo = context!!.packageManager.getPackageInfo(context!!.packageName, 0)
        sb.append("version_code= ${packageInfo.versionCode}\n")
        sb.append("version_name= ${packageInfo.versionName}\n")
        sb.append("package_name= ${packageInfo.packageName}\n")
        sb.append("requested_permission=\n ${Arrays.toString(packageInfo.requestedPermissions)}\n")//已申请到那些权限


        //统计一波 存储空间的信息，
        val memInfo = android.app.ActivityManager.MemoryInfo()
        val ams =
            context!!.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
        ams.getMemoryInfo(memInfo)


        sb.append("availMem= ${Formatter.formatFileSize(context, memInfo.availMem)}\n")//可用内存
        sb.append("totalMem= ${Formatter.formatFileSize(context, memInfo.totalMem)}\n")//设备总内存
        sb.append("canonicalName= ${MainActivity::class.java.canonicalName}\n")

        Log.e("getAndShowInfoDevice", sb.toString())
    }
}